package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.adapter.FootprintAdapter;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.Footprint;
import com.hemaapp.yjnh.bean.User;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 类描述：足迹列表Fragment
 * 创建人：GuiyouZhang
 * 创建时间：2016/8/2 20:37
 * 修改备注：
 */
public class FootPrintListFragment extends ViewPagerFragment {

    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.layout_refresh)
    RefreshLoadmoreLayout layoutRefresh;

    private User user;
    private int page = 0;
    private String lat = "";//纬度
    private String lng = "";//经度
    private String keytype = "";//获取类型	1：田家     2：有机    3：地标    4：村游    6：特产    7：走走    8：农需    9：乐乐    11：粮库

    private ArrayList<Footprint> mBlogs = new ArrayList<>();
    private FootprintAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_viewpager_refresh_list);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        lat = XtomSharedPreferencesUtil.get(getActivity(), "lat");
        lng = XtomSharedPreferencesUtil.get(getActivity(), "lng");
        if (savedInstanceState != null) {
            keytype = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", keytype);
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        layoutRefresh.setBackgroundColor(0xffffffff);
        layoutRefresh.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().historyList(user.getToken(), keytype, lng, lat, page+"");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().historyList(user.getToken(), keytype, lng, lat, page+"");
            }
        });
        if (keytype.equals("1")) {
            layoutRefresh.setBackgroundColor(0xfff0f0f0);
        }else {
            layoutRefresh.setBackgroundColor(0xffffffff);
        }
    }

    public void setKeytype(String keytype) {
        this.keytype = keytype;
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void setListener() {
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ACCESS_HISTORY_LIST:
            case ACCESS_HISTORY_CLEAR:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ACCESS_HISTORY_LIST:
            case ACCESS_HISTORY_CLEAR:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ACCESS_HISTORY_CLEAR:
                XtomToastUtil.showShortToast(getActivity(), "清空成功!");
                mBlogs.clear();
                mAdapter.notifyDataSetChanged();
                break;
            case ACCESS_HISTORY_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Footprint> fResult = (HemaPageArrayResult<Footprint>) baseResult;
                if (fResult == null || fResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    layoutRefresh.refreshSuccess();
                    mBlogs.clear();
                    mBlogs.addAll(fResult.getObjects());
                } else {// 更多
                    layoutRefresh.loadmoreSuccess();
                    if (fResult.getObjects().size() > 0) {
                        mBlogs.addAll(fResult.getObjects());
                    } else {
                        layoutRefresh.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ACCESS_HISTORY_CLEAR:
                XtomToastUtil.showShortToast(getActivity(), "清空失败," + baseResult.getMsg());
                break;
            case ACCESS_HISTORY_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(getActivity(), "操作失败," + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ACCESS_HISTORY_CLEAR:
                XtomToastUtil.showShortToast(getActivity(), "清空失败，请稍后再试");
                break;
            case ACCESS_HISTORY_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(getActivity(), "操作失败，请稍后再试");
                break;
        }
    }

    private void refreshData(final int failed) {
        if (mAdapter == null) {
            int type = 1;
            if (keytype.equals("4") || keytype.equals("7") || keytype.equals("9"))
                type = 2;
            else if (keytype.equals("1"))
                type = 3;
            mAdapter = new FootprintAdapter(getActivity(), mBlogs, type);
            mAdapter.setClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Footprint blog = mBlogs.get(position);
                    Intent intent = BaseUtil.createBlogIntent(getActivity(), blog.getType());
                    intent.putExtra("blog_id", blog.getBlog_id());
                    startActivity(intent);
                }
            });
            listview.setAdapter(mAdapter);
        } else
            mAdapter.notifyDataSetChanged();
        mAdapter.setFailtype(failed);
    }

    @Override
    public void fetchData() {
        getNetWorker().historyList(user.getToken(), keytype, lng, lat, page+"");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 清空当前页的历史记录
     */
    public void clearHistory() {
        if (mBlogs.size() == 0) {
            return;
        }
        HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
        hbDialog.setText("确定清空足迹吗?");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().historyClear(user.getToken(), keytype);
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }
}
